import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
  Settings,
  Power,
  PowerOff,
  ExternalLink,
  User,
  Calendar,
  Package,
  Zap,
  AlertCircle
} from 'lucide-react'
import { Button } from './ui/Button'
import { Badge } from './ui/Badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/Card'

interface PluginManifest {
  name: string
  version: string
  description?: string
  author?: string
  homepage?: string
  icon?: string
  tags?: string[]
  engines?: {
    host?: string
  }
}

interface PluginCardProps {
  plugin: {
    name: string
    manifest: string
    enabled: boolean
  }
  manifest?: PluginManifest
  onToggle: () => void
  onConfigure: () => void
  loading?: boolean
  compact?: boolean
}

export function PluginCard({
  plugin,
  manifest,
  onToggle,
  onConfigure,
  loading = false,
  compact = false
}: PluginCardProps) {
  const { t } = useTranslation()
  const [imageError, setImageError] = useState(false)

  const pluginId = plugin.name.split('/').pop() || plugin.name
  const displayName = manifest?.name || pluginId
  const description = manifest?.description || t('plugins.card.noDescription')
  const author = manifest?.author || t('plugins.card.unknown')
  const version = manifest?.version || '0.0.0'
  const tags = manifest?.tags || []
  
  // Generate a color based on plugin name for consistent theming
  const getPluginColor = (name: string) => {
    const colors = [
      'bg-blue-500', 'bg-green-500', 'bg-purple-500', 'bg-pink-500', 
      'bg-indigo-500', 'bg-yellow-500', 'bg-red-500', 'bg-teal-500'
    ]
    const hash = name.split('').reduce((a, b) => a + b.charCodeAt(0), 0)
    return colors[hash % colors.length]
  }

  const pluginColor = getPluginColor(pluginId)

  if (compact) {
    return (
      <Card className="hover:shadow-md transition-all duration-200">
        <CardContent className="p-4">
          <div className="flex items-center space-x-3">
            {/* Icon */}
            <div className="flex-shrink-0">
              {manifest?.icon && !imageError ? (
                <img 
                  src={manifest.icon} 
                  alt={displayName}
                  className="w-10 h-10 rounded-lg object-cover"
                  onError={() => setImageError(true)}
                />
              ) : (
                <div className={`w-10 h-10 rounded-lg ${pluginColor} flex items-center justify-center text-white`}>
                  <Package className="w-5 h-5" />
                </div>
              )}
            </div>

            {/* Info */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center space-x-2">
                <h3 className="font-medium text-sm truncate">{displayName}</h3>
                <Badge variant={plugin.enabled ? 'default' : 'secondary'} className="text-xs">
                  {plugin.enabled ? t('plugins.card.active') : t('plugins.card.inactive')}
                </Badge>
              </div>
              <p className="text-xs text-muted-foreground truncate">{description}</p>
            </div>

            {/* Actions */}
            <div className="flex items-center space-x-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={onConfigure}
                className="h-8 w-8 p-0"
              >
                <Settings className="h-4 w-4" />
              </Button>
              <Button
                variant={plugin.enabled ? 'destructive' : 'default'}
                size="sm"
                onClick={onToggle}
                disabled={loading}
                className="h-8 w-8 p-0"
              >
                {plugin.enabled ? <PowerOff className="h-4 w-4" /> : <Power className="h-4 w-4" />}
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="group hover:shadow-lg transition-all duration-300 hover:-translate-y-1">
      <CardHeader className="pb-3">
        <div className="flex items-start space-x-4">
          {/* Plugin Icon */}
          <div className="flex-shrink-0">
            {manifest?.icon && !imageError ? (
              <img 
                src={manifest.icon} 
                alt={displayName}
                className="w-16 h-16 rounded-xl object-cover border-2 border-border"
                onError={() => setImageError(true)}
              />
            ) : (
              <div className={`w-16 h-16 rounded-xl ${pluginColor} flex items-center justify-center text-white shadow-lg`}>
                <Package className="w-8 h-8" />
              </div>
            )}
          </div>

          {/* Plugin Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center space-x-2 mb-1">
              <CardTitle className="text-lg truncate">{displayName}</CardTitle>
              <Badge variant={plugin.enabled ? 'default' : 'secondary'}>
                {plugin.enabled ? (
                  <>
                    <Zap className="w-3 h-3 mr-1" />
                    Active
                  </>
                ) : (
                  'Inactive'
                )}
              </Badge>
            </div>
            
            <div className="flex items-center space-x-4 text-sm text-muted-foreground mb-2">
              <div className="flex items-center space-x-1">
                <User className="w-3 h-3" />
                <span>{author}</span>
              </div>
              <div className="flex items-center space-x-1">
                <Calendar className="w-3 h-3" />
                <span>v{version}</span>
              </div>
            </div>

            <CardDescription className="line-clamp-2">
              {description}
            </CardDescription>
          </div>

          {/* Status indicator */}
          <div className="flex-shrink-0">
            <div className={`w-3 h-3 rounded-full ${plugin.enabled ? 'bg-green-500' : 'bg-gray-300'}`} />
          </div>
        </div>

        {/* Tags */}
        {tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-3">
            {tags.slice(0, 3).map((tag) => (
              <Badge key={tag} variant="outline" className="text-xs">
                {tag}
              </Badge>
            ))}
            {tags.length > 3 && (
              <Badge variant="outline" className="text-xs">
                +{tags.length - 3} more
              </Badge>
            )}
          </div>
        )}
      </CardHeader>

      <CardContent className="pt-0">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Link to={`/plugins/${pluginId}`}>
              <Button variant="outline" size="sm" className="flex items-center space-x-1">
                <ExternalLink className="w-4 h-4" />
                <span>Details</span>
              </Button>
            </Link>
            
            <Button
              variant="ghost"
              size="sm"
              onClick={onConfigure}
              className="flex items-center space-x-1"
            >
              <Settings className="w-4 h-4" />
              <span>Configure</span>
            </Button>
          </div>

          <Button
            variant={plugin.enabled ? 'destructive' : 'default'}
            size="sm"
            onClick={onToggle}
            disabled={loading}
            loading={loading}
            className="flex items-center space-x-1"
          >
            {plugin.enabled ? (
              <>
                <PowerOff className="w-4 h-4" />
                <span>Disable</span>
              </>
            ) : (
              <>
                <Power className="w-4 h-4" />
                <span>Enable</span>
              </>
            )}
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
